import { defineStore } from 'pinia'
import type { IHandleApi } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { IPassword, IQueryPassword } from '@/types/password.ts'
import {
  addPasswordApi,
  deletePasswordApi,
  queryPasswordApi, queryPasswordCategoryApi,
  updatePasswordApi
} from '@/apis/password'

export const usePasswordStore = defineStore('password', {
  state: () => ({
    passwordList: [] as IPassword[],
    queryInfo: {
      category: '',
      owner: '哥哥'
    } as IQueryPassword,
    passwordApiType: 'ADD' as IHandleApi,
    categoryList: [] as string[],
    currentPassword: {
      title: '',
      website: '',
      username: '',
      password: '',
      category: '',
      owner: '',
      remark: ''
    } as IPassword,
    isScrollEnd: false,
    isRefresh: false
  }),
  actions: {
    async queryPasswordList() {
      this.passwordList = await queryPasswordApi(this.queryInfo)
    },
    async queryPasswordCategory() {
      this.categoryList = await queryPasswordCategoryApi()
    },
    async handlePasswordApi(password: IPassword) {
      switch (this.passwordApiType) {
        case 'ADD':
          await addPasswordApi(password)
          ElMessage.success('新增密码记录成功')
          break
        case 'UPDATE':
          await updatePasswordApi(password.id as number, password)
          ElMessage.success('更新密码记录成功')
          break
        case 'DELETE':
          await deletePasswordApi(password.id as number)
          ElMessage.success('删除密码记录成功')
          break
        default:
          break
      }
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryPasswordList()
      this.isRefresh = !this.isRefresh
    },
    getEmptyPassword(): IPassword {
      return {
        category: '',
        owner: '',
        password: '',
        remark: '',
        title: '',
        username: '',
        website: ''
      }
    }
  }
})
